<?php

require_once("config.php");
require_once("db.php");

function pie()
{
	global $mainURL;
	print '<div id="pie">
	<a href="http://code.google.com/p/sweetter/">Sweetter 2.0</a> followers, followers, followers...
	</div>';
}

function checkUser($user, $pass)
{
	$q = sprintf("SELECT * FROM users WHERE name='%s' and password='%s'", 
	mysql_real_escape_string($user), mysql_real_escape_string(md5($pass)));
	$res = mysql_query($q);
	return mysql_num_rows($res);
}


function existsUser($user)
{
	$q = sprintf("SELECT * FROM users WHERE name='%s'", mysql_real_escape_string($user));
	$res = mysql_query($q);
	return mysql_num_rows($res) == 1;
}

// TODO: be able to use less chars depeding on karma
function userChars($user)
{
	return 133;
}

function show_header($text)
{
	global $mainURL;
	print '<a href="'.$mainURL.'" title="P&aacute;gina principal"><img src="'.$mainURL.'/img/logo.png" alt="sweetter"/></a><h1>'.$text.'</h1>';
}

function validUser($user)
{
	if(!preg_match("/^[a-z_][a-z0-9_]{2,}$/i", $user))
	{
		return false;
    }
	if(preg_match("/^(css|js|avatar|img|svg)$/", $user))
	{
		return false;
    };
	return true;
}

function sweet_check()
{
	global $sweet;
	global $userg;
	
	$sweet = $_GET['sweet'];
	if(!preg_match("/^[0-9_]{0,20}$/", $sweet))
	{
		header("Location: $mainURL/404.php");
	}
	
	$q = sprintf("SELECT * FROM sweets,users WHERE id='%s' and name=userid",
	mysql_real_escape_string($sweet));
	$res = mysql_query($q);
	if(mysql_num_rows($res) != 1)
	{
		header("Location: $mainURL/404.php");
	}
	if (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
		$userg = $row['name'];
	}
}

function session_check($thisIsMain = false)
{
	global $userg;
	global $my_user;
	global $user;
	global $mainURL;

	$my_user = false;
	
	session_start();
	
	// If there's a user GET string
	if (!empty($_GET['user'])) {
		$userg = $_GET['user'];
	}
	//TODO comprobar el userg
	if ((!isset($_SESSION) || empty($_SESSION['auth'])) && isset($userg) && $userg == '' && !$thisIsMain) {
		header("Location: $mainURL");
    }

	if(isset($_SESSION) && !empty($_SESSION['auth'])) {
		$user = $_SESSION['auth'];
		$my_user = ($userg == $user) ? true : false;
	}
}


// From http://www.ilovejackdaniels.com/php/email-address-validation
function check_email_address($email) {
  // First, we check that there's one @ symbol, and that the lengths are right
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
    return false;
  }
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
     if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
      return false;
    }
  }  
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}

function show_comments($page=0){
    global $userg;
    global $userURL;
    $limit = 10;
    $followers = know_followees($userg);
    $or_uid = "userid='" . mysql_real_escape_string($userg) . "' ";
    foreach ($followers as $key => $value){
        if ($value != $userg)
            $or_uid .= "or userid='" . mysql_real_escape_string($value) . "' ";
    }
    $q = sprintf("select id, comment, date, userid from sweets where %s 
        order by date desc 
        limit %d,%d",
        $or_uid, $page*$limit, $limit);
    $res = mysql_query($q);
    $i = 0;
    while (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
        $i++;
        show_one_comment($row);
        }
}

function show_sweet(){

    global $userURL;
    global $sweet;

    $limit = 5;
    $q = sprintf("select id, comment, date, userid from sweets where id='%s'",
        mysql_real_escape_string($sweet));
    $res = mysql_query($q);
    if (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
        show_one_comment($row);
        }
}

function show_index_comments(){

    global $userURL;

    $limit = 5;
    $q = sprintf("select id, comment, date, userid from sweets 
        order by date desc 
        limit %d",
        $limit);
    $res = mysql_query($q);
    $i = 0;
    while (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
        $i++;
        show_one_comment($row);
        }
}

function show_one_comment($row){
	global $userURL;
	global $sweetURL;
	$date = $row['date'];
	$id = $row['id'];
	$comment = htmlentities($row['comment']);
	$comment = str_replace("&amp;","&", $comment);
	$comment = str_replace("\'","'", $comment);
	$comment  = ereg_replace ('(https?://[a-z0-9-]+(\.[a-z0-9-]+)+([^ ]+)?)', '<a href="\1">\1</a>', $comment);
	$comment  = ereg_replace ('@([a-zA-Z0-9_/-]*)', '@<a href="'.$userURL.'\1">\1</a>', $comment);
	$u = $row['userid'];
	$avatar = know_user_attr($u, "avatar");

	show_one_bubble($u, $id, $comment, $avatar, $date);
}



function show_one_bubble($u, $id, $content, $avatar, $date)
{
	global $userURL;
	global $sweetURL;
?>
	<div class="entry">
		<div class="person-info">
		<a href="<?=$userURL.$u?>">
			<img class="face" src="<?=$avatar?>" alt="<?=$u?>">
			<br/>
			<?=$u?>
		</a>
		</div>

		<div class="post">
			<div class="post2">
				<div class="post-header" style="height: 40px;">
					<h4 class="post-title">
						<a href="<?=$sweetURL.$id?>">&nbsp;</a>
					</h4>
				</div>
				
				<div class="post-contents">
					<div>
						<p>
						<?=$content?>
						</p>
					</div>
				</div>
				
				<div class="post-footer">
					<p>
						<a href="<?=$sweetURL.$id?>"><?=$date?></a>
					</p>
				</div>
			</div>
		</div>
	</div>
<?php
}

function show_followers(){
    global $userg;
    global $user;
    global $userURL;

    $q = "select follower from followers where followee='". mysql_real_escape_string($userg) ."'";
    $res = mysql_query($q);
    $n = 0;
    $idx = '';
    while($value = mysql_fetch_array($res, MYSQL_ASSOC))
    {
        if($value['follower'] == $user)
            $idx = 'id="me"';
        else $idx = '';
        $n++;
        print '<div class="follower" '.$idx.'><a href="'.$userURL.$value['follower'].'">'.$value['follower'].'</a></div>';
    }
    print '</div>';
    print '<div><span id="nfollowers">' . $n . '</span> followers </div>';
    if($user){
        $follow = 'follow this';
        $q = "select * from followers where followee='". mysql_real_escape_string($userg) ."' and follower='". mysql_real_escape_string($user) ."'";
        $res = mysql_query($q);
        if(mysql_num_rows($res) > 0)
            $follow = 'not follow';

        print '<div id="follow"><input type="button" id="follow_this" value="'.$follow.'"/></div>';
    }
}

//esta funcion devuelve en un array todos los followers de un user
function know_followers($uid){
    $q = "select follower from followers where followee='". mysql_real_escape_string($uid) ."'";
    $res = mysql_query($q);
    $ret = array();
    $i = 0;
    while($value = mysql_fetch_array($res, MYSQL_ASSOC)){
        $ret[$i] = ($value['follower']);
        $i++;
    }
    return $ret;
}

function know_followees($uid){
    $q = "select followee from followers where follower='". mysql_real_escape_string($uid) ."'";
    $res = mysql_query($q);
    $ret = array();
    $i = 0;
    while($value = mysql_fetch_array($res, MYSQL_ASSOC)){
        $ret[$i] = ($value['followee']);
        $i++;
    }
    return $ret;
}

function know_todo($uid){
    $q = "select sweetid from todo where asigned='". mysql_real_escape_string($uid) ."' and doit=false";
    $res = mysql_query($q);
    $value = mysql_num_rows($res);
    return $value;
}

function know_user_attr($uid, $attr){
    $q = "select ".$attr." from users where name='". mysql_real_escape_string($uid) ."'";
    $res = mysql_query($q);
    $i = 0;
    $value = mysql_fetch_array($res, MYSQL_ASSOC);
    return (empty($value[$attr])) ? "img/none.png" : $value[$attr];
}
function know_user_attrs($uid, $attrs){
    $q = "select ".$attrs." from users where name='". mysql_real_escape_string($uid) ."'";
    $res = mysql_query($q);
    $i = 0;
    $value = mysql_fetch_array($res, MYSQL_ASSOC);
    return $value;
}

function edit_profile($uid, $avatar, $nmail, $nlocation, $pass0, $pass1, $pass2){
    $errores = '';
    $attrs = know_user_attrs($uid, "password, email, location");
    if(empty($attrs)){
        return "error";
    }
    $pass = $attrs['password'];
    $to_up2 = "password='".$pass."'";
    $email = $attrs['email'];
    $to_up1 = "email='".$email."'";
    $location = $attrs['location'];
    $to_up3 = "location='".$location."'";
    if ($nmail != $email){
        if (check_email_address($nmail))
            $to_up1 = sprintf("email='%s'", mysql_real_escape_string(htmlentities($nmail)));
        else
            $errores .= "correo mal<br/>";
    }
    if ($location != $nlocation){
        $to_up3 = sprintf("location='%s'", mysql_real_escape_string(htmlentities($nlocation)));
    }

    if ($pass0 != '' && $pass1 != '' && $pass2 != ''){
        if (md5($pass0) == $pass)
            if ($pass1 != $pass2)
                $errores .= "no coinciden los password<br/>";
            else{
                $to_up2 = sprintf("password='%s'", mysql_real_escape_string(md5($pass1)));
            }
        else{
            $errores .= "El password es incorrecto<br/>";
        }

    }
    if(!empty($errores))
        return $errores;
    $res = new_user_attrs($uid, $to_up1.",".$to_up2.", ".$to_up3);
    if($res)
        return '';
    else return 'error';
}

function show_profile($user, $me=''){
    global $userURL;
    global $mainURL;

        $attrs = know_user_attrs($user, "location, avatar");
        $location = substr($attrs['location'], 0, 26); // máximo 26 caracteres
        $avatar = $attrs['avatar'];
        if(empty($attrs))
            return "show_profile error";

        if (!empty($me)){
        print '<div id="loginp"><a href="'.$mainURL.'?quit">'.$me.' logout</a></div>';
	print '<div id="myprofile"><a href="'.$userURL.$me.'">my sweetter</a></div>';
    }
        if(!empty($avatar))
            print '<div id="avatar"><img src="'.$avatar.'"/></div>';
        print '<div id="location">location: '.$location.'</div>';

        if (!empty($me))
        print '<div><a href="edit_profile.php">edit profile</a></div>';

  $ntodo = know_todo($user);
  print '<div id="todo">';
  print '<a href="'.$userURL.$user.'?todo=1">TODO list ('.$ntodo.')</a>';
  print '</div>';
}

function  image_valid($type)
{
    $file_types  = array(  
    'image/jpeg'    => 'jpg',
    'image/jpeg'    => 'jpeg',
    'image/gif'     => 'gif',
    'image/PNG'     => 'png',
    'image/png'     => 'png',
    'image/JPG'     => 'jpg',
    'image/GIF'     => 'gif',
    'image/bmp'     => 'bmp',
    'image/bmp'     => 'BMP',
    );
   
    if(!array_key_exists($type, $file_types))
    	return -1;
    else
    	return $file_types[$type];
}

function new_user_attrs($user, $attrs){
    $q = "update users set ".$attrs." where name='". mysql_real_escape_string($user) ."'";
    $res = mysql_query($q);
    return $res;
}


function image_upload($user, $files){
    $error = "";
    $avatar = know_user_attr($user, "avatar");
    $target_path = "avatar/";
    $extension = image_valid($files['avatar']['type']);
    if ($extension == -1)
    {
        $error .= "tipo de imagen no v&aacute;lido<br/>";
    }
    $target_path = $target_path . $user . $extension;
    list($width, $height, $type, $attr) = getimagesize($files['avatar']['tmp_name']);

    if($width > 64 || $height > 64)
        $error .= "imagen demasiado grande. Max 64x64<br/>";
    else{
        if(!image_save_and_resize($files['avatar']['tmp_name'], $target_path))
            $error .= "error al subir el avatar<br/>";
        else{
            if (!empty($avatar))
                unlink($avatar);
            new_user_attrs($user, "avatar='".$target_path."'");
        }
    }
    return $error;
}

/**
 * Creates an image in $target_path like the one in $upfile but resized to a maximum of 64x64
 */
function image_save_and_resize($upfile, $target_file)
{
	list($width, $height, $type, $attr) = getimagesize($upfile);
	// Max height and width
	$max_width = 64;
	$max_height = 64;
	
	// Proportionally resize the image to the
	// max sizes specified above
	
	$x_ratio = $max_width / $width;
	$y_ratio = $max_height / $height;

	if( ($width <= $max_width) && ($height <= $max_height) )
	{
		$tn_width = $width;
		$tn_height = $height;
	}
	elseif (($x_ratio * $height) < $max_height)
	{
		$tn_height = ceil($x_ratio * $height);
		$tn_width = $max_width;
	}
	else
	{
		$tn_width = ceil($y_ratio * $width);
		$tn_height = $max_height;
	}
	
	// Create the new image!
	$src = ImageCreateFromJpeg($upfile);
	$dst = ImageCreateTrueColor($tn_width, $tn_height);
	ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
	ImageJpeg($dst, $target_file);
	// Destroy the images
	ImageDestroy($src);
	ImageDestroy($dst);
}

function show_todo_comments($page=0, $all=false){
    global $userg;
    global $my_user;
    global $sweetURL;
    global $userURL;
    
    $limit = 10;
    $q = sprintf("select id, comment, date, userid, doit from sweets,todo where asigned='%s' and sweets.id = todo.sweetid
        order by date 
        limit %d,%d",
        mysql_real_escape_string($userg), $page*$limit, $limit);
    $res = mysql_query($q);
    $i = 0;
    while (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
        $i++;
        $date = $row['date'];
        $comment = htmlentities($row['comment']);
        $comment = str_replace("&amp;","&", $comment);
        $comment = str_replace("\'","'", $comment);
        $comment  = ereg_replace ('(https?://[a-z0-9-]+(\.[a-z0-9-]+)+([^ ]+)?)', '<a href="\1">\1</a>', $comment);
        $comment  = ereg_replace ('@([a-zA-Z0-9_/-]*)', '@<a href="'.$userURL.'\1">\1</a>', $comment);
        $u = $row['userid'];
        $doit = $row['doit'];
        $doitid = $row['id'];
        $doit_to_show ='';
        if ($my_user){
            $doit_to_show ='<a href="" class="doit" id='.$doitid.'>doit</a>';
        }

        $avatar = know_user_attr($u, "avatar");
        if ($doit & $all)
            $comment = '<strike>@<a href="'.$userURL.$u.'">'.$u.'</a> :: '.$comment.'</strike>';
        else if(!$doit)
            $comment = "$comment $doit_to_show";
        else continue;

        show_one_bubble($u, $id, $comment, $avatar, $date);
    }
}


function show_todo_comments_rss($all=false){
    global $userg;
    global $my_user;
    global $sweetURL;
    global $userURL;

    $limit = 10;
    $q = sprintf("select id, comment, date, userid, doit from sweets,todo where asigned='%s' and sweets.id = todo.sweetid
        order by date 
        limit %d,%d",
        mysql_real_escape_string($userg), 0, $limit);
    $res = mysql_query($q);
    $i = 0;
    while (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
        $i++;
        $date = $row['date'];
        $title = $row['comment'];
        $title = str_replace("<","&lt;", $title);
        $title = str_replace(">","&gt;", $title);
        $title = ereg_replace("&(.)acute;",'\1', $title);
        $title = str_replace("&ntilde;","ñ", $title);
        $title = str_replace("&Ntilde;","Ñ", $title);
        $title = substr($title, 0, 90);
        $comment = htmlentities($row['comment']);
        $comment = str_replace("&amp;","&", $comment);
        $comment = str_replace("\'","'", $comment);
        $comment  = ereg_replace ('(https?://[a-z0-9-]+(\.[a-z0-9-]+)+([^ ]+)?)', '<a href="\1">\1</a>', $comment);
        $comment  = ereg_replace ('@([a-zA-Z0-9_/-]*)', '@<a href="'.$userURL.'\1">\1</a>', $comment);
        $u = $row['userid'];
        $doit = $row['doit'];
        $doitid = $row['id'];

        $avatar = know_user_attr($u, "avatar");

        if ($doit & $all)
            $comment = $avatar.'<strike>@<a href="'.$userURL.$u.'">'.$u.'</a> :: '.$comment.'</strike>';
        else if(!$doit)
            $comment = $avatar.'@<a href="'.$userURL.$u.'">'.$u.'</a> :: '.$comment;
?>
		<item>
			<title><?php echo $u.": ".$title; ?></title>
			<link><?php echo $userURL.$u; ?></link>
			<pubDate><?php echo $date; ?></pubDate>
			<dc:creator><?php echo $u; ?></dc:creator>
			<guid><?php echo $sweetURL.$doitid; ?></guid>
			<description><?php echo htmlentities($avatar.'<a href="'.$userURL.$u.'">'.$u.'</a> :: '.$comment);?></description>
		</item>
<?php
    }
}

function show_index_comments_rss($all=false){
    global $userURL;
    $limit = 10;
    $followers = know_followees($userg);
    $q = sprintf("select id, comment, date, userid from sweets
        order by date desc 
        limit %d,%d",
        0, $limit);
    $res = mysql_query($q);
    $i = 0;
    while (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
        $i++;
        show_one_comment_rss($row);
        }
}


function show_comments_rss(){
    global $userg;
    global $userURL;
    $limit = 10;
    $followers = know_followees($userg);
    $or_uid = "userid='" . mysql_real_escape_string($userg) . "' ";
    foreach ($followers as $key => $value){
        if ($value != $userg)
            $or_uid .= "or userid='" . mysql_real_escape_string($value) . "' ";
    }
    $q = sprintf("select id, comment, date, userid from sweets where %s 
        order by date desc 
        limit %d,%d",
        $or_uid, 0, $limit);
    $res = mysql_query($q);
    $i = 0;
    while (($row = mysql_fetch_array($res, MYSQL_ASSOC))){
        $i++;
        show_one_comment_rss($row);
        }
}

function show_one_comment_rss($row) {
	global $userURL;
	global $sweetURL;
	$date = $row['date'];
	$id = $row['id'];
	$title = $row['comment'];
	$title = str_replace("<","&lt;", $title);
	$title = str_replace(">","&gt;", $title);
	$title = ereg_replace("&(.)acute;",'\1', $title);
	$title = str_replace("&ntilde;","ñ", $title);
	$title = str_replace("&Ntilde;","Ñ", $title);
	$title = substr($title, 0, 90);
	$comment = htmlentities($row['comment']);
	$comment = str_replace("&amp;","&", $comment);
	$comment = str_replace("\'","'", $comment);
	$comment  = ereg_replace ('(https?://[a-z0-9-]+(\.[a-z0-9-]+)+([^ ]+)?)', '<a href="\1">\1</a>', $comment);
	$comment  = ereg_replace ('@([a-zA-Z0-9_/-]*)', '@<a href="'.$userURL.'\1">\1</a>', $comment);
	$u = $row['userid'];
	$avatar = know_user_attr($u, "avatar");
	if (!empty($avatar))
		$avatar = '<img class="avatar" src="'.$avatar.'"/>';
?>
		<item>
			<title><?php echo $u.": ".$title; ?></title>
			<link><?php echo $userURL.$u; ?></link>
			<pubDate><?php echo $date; ?></pubDate>
			<dc:creator><?php echo $u; ?></dc:creator>
			<guid><?php echo $sweetURL.$id; ?></guid>
			<description><?php echo htmlentities($avatar.'<a href="'.$userURL.$u.'">'.$u.'</a> :: '.$comment);?></description>
		</item>
<?php
}



?>
